import { observable, action, toJS } from "mobx";
import { WeaForm } from 'comsMobx'
import { WeaLocaleProvider, WeaSelect, WeaBrowser, WeaError } from 'ecCom';
import API from '../apis/mode';
import { message } from 'antd';
import { Fragment } from "react";
const getLabel = WeaLocaleProvider.getLabel;

export default class FileUploadStore {

    @observable visible = false;
    @observable modeId = '0';
    @observable formId = '0';
    @observable fieldcount = 0;
    @observable fileformat = "";
    @observable empowmentType = "0";
    @observable isChangeFlag = "0";
    @observable isChangeFlagTemp = "0";   //用于保存临时值，如果没有调用附件保存，则不改变实际的标志
    @observable isChangeEmpowmentType = "1,0";
    @observable fileUploadSetForm = new WeaForm();  //附件上传设置的form
    @observable fileUploadSetCondition = [];        //附件上传设置的condition
    @observable mainselectOption = "";                   //默认上传目录的初始值
    @observable currentPage = 1;
    @observable currentPagesize = 10;
    @observable dataTotal = 10;

    @observable specialSetColumns = [];             //特殊设置的列
    @observable specialSetDatas = [];               //特殊设置编辑列表的datas
    @observable specialSetParams = {};              //特殊设置的列表参数

    @observable categorytype = null;//目录类型
    @observable seccategory = null;//目录id
    @observable selectcategory = null;//选择目录的select字段

    @observable fileisdisplay = 1;                //附件上传人和时间是否显示
    selectcategory_err = [];
    //附件上传特殊设置的 附件上传目录 必填校验
    @action
    initNames = (obj) => {
        Object.keys(obj).forEach(key => {
            if (key == 'empowmentType') {
                if (obj[key].value) {
                    const empow = obj[key].value.split(",");

                    this.empowmentType = empow[0];
                    this.isChangeFlag = empow.length == 2 ? empow[1] : "0";
                    this.isChangeFlagTemp = this.isChangeFlag;
                }
            } else if (key === 'fileFormat' || key ==='fileisdisplay') {
                this[key.toLocaleLowerCase()] = obj[key]['value'];
            }else {
                this[key] = obj[key];
            }
        })
    }

    @action
    setFieldName = (name, value) => {
        if (name == 'empowmentType') {
            if (value) {
                const empow = value.split(",");

                this.empowmentType = empow[0];
                this.isChangeFlag = empow.length == 2 ? empow[1] : "0";
                this.isChangeFlagTemp = this.isChangeFlag;
            }
        } else {
            this[name] = value;
        }
    }

    @action
    setModeid = (modeid) => {
        this.modeId = modeid;
    }

    @action
    setFormid = (formid) => {
        this.formId = formid;
    }

    @action
    setIsChangeFlag = (isChangeFlag) => {
        this.isChangeFlagTemp = isChangeFlag;
    }

    @action
    getEmpowmentType = () => {
        this.isChangeEmpowmentType = this.empowmentType + "," + this.isChangeFlag;
        return this.isChangeEmpowmentType;
    }

    @action
    initFileUploadSet = () => {
        this.fileUploadSetForm = new WeaForm();  //附件上传设置的form
        this.fileUploadSetCondition = [];        //附件上传设置的condition
        this.mainselectOption = "";              //默认选择目录选项值
        this.specialSetColumns = [];
        this.specialSetDatas = [];
        this.specialSetParams = {};              //特殊设置的列表参数

    }

    @action
    saveUploadFileInfo = () => {
        if (!this.checkSpacialSetParams()) return; // 特殊设置-附件上传目录 必填校验
        this.isChangeFlag = this.isChangeFlagTemp;

        const params = {
            modeId: this.modeId, 
            formId: this.formId, 
            ...this.specialSetParams, 
            fileformat_main: this.fileformat, 
            empowmentType_main: this.getEmpowmentType(), 
            categorytype_main: this.categorytype.value, 
            seccategory_main: this.seccategory.value, 
            selectcategory_main: this.selectcategory.value, 
            fileisdisplay: this.fileisdisplay 
        };
        API.saveUploadFileInfo(params).then(({ count, status }) => {
            this.fieldcount = count;
            if (status == "1") {
                message.destroy();
                message.success(getLabel(18758, "保存成功"));
            } else {
                message.error(getLabel(127353, "错误"));
            }

        })
    }

    @action
    getUploadFieldInfo = () => {
        const params = { 
            modeId: this.modeId, 
            formId: this.formId, 
            current: this.currentPage, 
            pageSize: this.currentPagesize 
        };

        API.getUploadFieldInfo(params).then((data) => {
            this.specialSetDatas = data && data['datas'];
            this.specialSetColumns = data && data['columns'];
            this.mainselectOption = data && data['field'];
            this.dataTotal = data && data['count'];
            this.reconstructColumns(); //重构columns结构
            data && this.formateSpecialSetParams();
        })
    }

    @action
    getUploadFieldInfoMOBX = (current, pageSize) => {
        const params = { 
            modeId: this.modeId, 
            formId: this.formId, 
            current: current, 
            pageSize: pageSize ? pageSize : this.currentPagesize, 
        };

        this.currentPage = current;
        this.currentPagesize = pageSize ? pageSize : this.currentPagesize;
        API.getUploadFieldInfo(params).then((data) => {
            this.specialSetDatas = data && data['datas'];
            this.specialSetColumns = data && data['columns'];
            this.mainselectOption = data && data['field'];
            this.dataTotal = data && data['count'];
            this.reconstructColumns(); //重构columns结构
            data && this.formateSpecialSetParams();
        })
    }

    //获取特殊设置列表参数
    @action
    formateSpecialSetParams = (datas) => {
        if (datas) {
            this.specialSetDatas = datas;
        } else {
            datas = [...this.specialSetDatas];
        }
        this.specialSetParams = {};
        let fieldIds = "";
        let flag = false;
        datas.map((item, index) => {
            this.specialSetParams['annexField_' + item.fieldId] = item.annexField;
            if (index == 0) {
                fieldIds += item.fieldId;
            } else {
                fieldIds += "," + item.fieldId;
            }
            this.specialSetParams['catalogType_' + item.fieldId] = item.catalogType[0];
            if (item.catalogType[0] === "0" && item.catalogType[1] && item.catalogType[1].replaceDatas[0]) {
                this.specialSetParams['seccategory_' + item.fieldId] = item.catalogType[1].replaceDatas[0].id;
                if (item.catalogType[1].replaceDatas[0].id) {
                    flag = true;
                }
                //this.specialSetParams['pathcategory_' + item.fieldId] = item.catalogType[1].replaceDatas[0].name;
            } else if (item.catalogType[0] === "1") {
                this.specialSetParams['selectfieldid_' + item.fieldId] = item.catalogType[1];
                if (item.catalogType[1]) {
                    flag = true;
                }
            }
            this.specialSetParams['fileFormatType_' + item.fieldId] = item.limitType[0];
            this.specialSetParams['fileFormat_' + item.fieldId] = item.limitType[1];
            this.specialSetParams['maincategory_' + item.fieldId] = item.maincategory;
            this.specialSetParams['subcategory_' + item.fieldId] = item.subcategory;
            this.specialSetParams['type_' + item.fieldId] = item.type;

        })
        if (flag) {
            this.setIsChangeFlag("1");
        } else {
            this.setIsChangeFlag("0");
        }
        this.specialSetParams['fieldIds'] = fieldIds;
    }

    /** 特殊设置的必填校验 */
    @action
    checkSpacialSetParams = () => {
        const params = { ...toJS(this.specialSetParams) };
        const fieldIdsArr = (params).fieldIds.split(',');
        for (let i = 0; i < fieldIdsArr.length; i++) {
            if (params['catalogType_' + fieldIdsArr[i]] == '1' && !params['selectfieldid_' + fieldIdsArr[i]]) {
                this.selectcategory_err[fieldIdsArr[i]].showError();
                return false;
            }
        }
        return true;
    }

    /** 给columns的附件上传目录列，增加render方法 */
    reconstructColumns = () => {
        const specialSetDatas = [...toJS(this.specialSetDatas)];
        if (specialSetDatas.length > 0) {
            // 处理datas数据
            for (let i = 0; i < specialSetDatas.length; i++) {
                (specialSetDatas[i]).com.fileUploadCatelog[0].compDef.subChildren[1].viewAttr = '3';
                (specialSetDatas[i]).com.fileUploadCatelog[0].compDef.subChildren[1].options[0].selected = false;
                // (this.specialSetDatas[i] as any).com.fileUploadCatelog[0].compDef.subChildren[1].style.width = 164;
            }
            // 处理columns数据
            (this.specialSetColumns)[1] = {
                ...(this.specialSetColumns)[1],
                render: (text, record, index) => {
                    return (<Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@lsuz39`}>
                        <div className="cube-wea-form-item-float-left">
                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@f9xebw`}
                                options={record.com.fileUploadCatelog[0].compDef.options}
                                value={record.catalogType[0]}
                                viewAttr={2}
                                onChange={(v) => this.updateSpecialSetParams(index, 'catalogType', v)}
                            />
                        </div>
                        {record.catalogType[0] == 0 && <div className="cube-wea-form-item-float-left">
                            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@99skuw`}
                                type={"doccategory"}
                                fieldName="seccategory"
                                // title={record.com.fileUploadCatelog[0].compDef.subChildren[0].title}
                                title="文档目录"
                                icon="icon-coms-doc"
                                iconBgcolor="#F14A2D"
                                style={{ width: 160 }}
                                replaceDatas={record.catalogType[1] ? record.catalogType[1].replaceDatas : []}
                                onChange={(value, valueSpan, valueObj) => this.updateSpecialSetParams(index, 'seccategory', valueObj)}
                            />
                        </div>}
                        {record.catalogType[0] == 1 && <div className="cube-wea-form-item-float-left">
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@l8vozz`} tipPosition='top' error={'"' + getLabel(22210, "附件上传目录") + '"' + getLabel(21423, "未填写")}
                                ref={v => this.selectcategory_err[record.fieldId] = v}
                            >
                                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@g70ue8`}
                                    options={record.com.fileUploadCatelog[0].compDef.subChildren[1].options}
                                    style={{ width: 160 }}
                                    viewAttr={3}
                                    value={!!record.catalogType[1] ? record.catalogType[1] : ''}
                                    onChange={(v) => this.updateSpecialSetParams(index, 'selectcategory', v)}
                                />
                            </WeaError>
                        </div>}
                    </Fragment>)
                }
            };
        }
        this.specialSetDatas = [...specialSetDatas];
    }

    updateSpecialSetParams = (index, field, value) => {
        const datas = [...toJS(this.specialSetDatas)];
        if (field === 'catalogType') {
            datas[index][field] = [value];
        } else if (field === 'seccategory') {
            datas[index].catalogType[1] = { replaceDatas: value };
            // datas[index][field] = value;
        } else if (field === 'selectcategory') {
            datas[index].catalogType[1] = value;
            // datas[index][field] = value;
        }

        this.formateSpecialSetParams(datas);
    }
}
